package com.twu.biblioteca.Users;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by ppeter on 03/10/2014.
 */
public class LoginManager {
    private static LoginManager instance = null;

    private Map<String, User> userTable;
    private User activeUser;


    private LoginManager() {
        userTable = new HashMap<String, User>();
        activeUser = null;
    }

    public static LoginManager getInstance() {
        if (instance == null) {
            instance = new LoginManager();
        }
        return instance;
    }

    public static void reset(){
        instance = null;
    }

    public User getLoggedInUser(){
        return activeUser;
    }

    public boolean isLoggedIn(){
        if(getLoggedInUser() != null){
            return true;
        }
        return false;
    }

    public boolean login(String userId, String password){
        if(isLoggedIn()){
            return false;
        }
        if(userTable.containsKey(userId)) {
            if (userTable.get(userId).checkPassword(password)) {
                activeUser = userTable.get(userId);
                return true;
            }
        }
        return false;
    }

    public void logout(){
        activeUser = null;
    }

    public boolean addUser(User user){
        if (userTable.containsKey(user.getId())) {
            return false;
        }
        userTable.put(user.getId(), user);
        return true;
    }

    public User getUser(String userId){
        if (userTable.containsKey(userId)) {
            return userTable.get(userId);
        }
        return null;
    }
}
